package com.ins1st.util;

import com.ins1st.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * @program: ins1st-cloud
 * @description:
 * @author: coderSun
 * @create: 2019-11-19 13:20
 **/
public class ShiroUtil {


    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static SysUser getUser() {
        return (SysUser) getSubject().getPrincipal() == null ? null : (SysUser) getSubject().getPrincipal();
    }

    public static void updateUser(SysUser sysUser) {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection =
                new SimplePrincipalCollection(sysUser, realmName);
        subject.runAs(newPrincipalCollection);
    }

    public static boolean check(String role) {
        if (StringUtils.isNotBlank(role)) {
            if (getSubject().hasRole(role)) {
                return true;
            }
        }
        return false;
    }


}
